/*!
 * Copyright (c) 2023-present StarDreamNet
 */
(document.loader || (document.loader = [])).push(["sendpost", class {
    constructor() {
        // 当前编辑器容器
        this.editor = null;
    };

    init_(require) {
        this.resize = require("index").resize;
        this.initEditorMD();
        this.initTitle();
    }

    checkPost(title, content) {
        if (!title || !content) return false;
        if (title.length >= 100 || content.length >= 100000) return false;
        return true;
    }

    initEditorMD() { // 初始化编辑器
        const loop = setInterval(() => {
            this.resize();
        }, 100);
        const _this = this;

        this.editor = editormd("test-editor", {
            height: 500, // 高度
            path: "/static/editormd/lib/", // 资源文件路径

            imageUpload: true, // 允许上传图片
            imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"], // 允许上传的图片文件类型
            imageUploadURL: "../../api/upload/", // 图片上传接口路径

            emoji: true, // 允许使用表情
            toc: true,
            tocm: true,
            taskList: true,
            codeFold: true, // 允许代码折叠
            tex: true,
            htmlDecode: false, // 是否编码 html
            flowChart: true,
            sequenceDiagram: true,
            searchReplace: true, // 允许搜索/替换
            saveHTMLToTextarea: true,

            toolbarIcons() { // 工具栏内容
                return editormd.toolbarModes.full.concat("|", "upload", "download")
            },

            toolbarIconsClass: { // 工具栏每个内容的图标
                upload: "fa-upload",
                download: "fa-download",
            },

            toolbarHandlers: {
                upload() { // 工具栏每个内容的方法
                    var input = document.createElement("input");
                    input.type = "file";
                    input.accept = ".md,.txt"; // 允许接受.md和.txt文件

                    input.onchange = () => { // 选择完毕后
                        const [file] = input.files; // 获取文件
                        const reader = new FileReader(); // 创建一个文件读取对象

                        reader.onload = () => { // 获取成功
                            const text = reader.result; // 获取文件内容

                            swal({
                                title: "选择导入方式",
                                buttons: {
                                    cancel: "取消",
                                    confirm: false,
                                    z0: {
                                        text: "追加到末尾",
                                        value: "0",
                                    },
                                    z1: {
                                        text: "粘贴到光标",
                                        value: "1",
                                    },
                                    z2: {
                                        text: "覆盖",
                                        value: "2",
                                    },
                                }
                            }).then(v => {
                                if (!v) return;
                                switch (v) {
                                    case "0": // 追加到末尾
                                        const markdown = this.getMarkdown();
                                        this.setMarkdown(markdown + text);
                                        break;
                                    case "1": // 粘贴到光标
                                        this.insertValue(text);
                                        break;
                                    case "2": // 覆盖
                                        this.setMarkdown(text);
                                        break;
                                    default:
                                        break;
                                }
                            })
                        };

                        reader.onerror = () => { // 读取失败
                            dsnackbar('warning', "导入失败");
                        };

                        reader.readAsText(file); // 读取该文件的内容
                    }

                    input.click(); // 模拟点击
                },
                download() { // 下载
                    const markdown = this.getMarkdown(); // 获取内容
                    var objurl = (URL || webkitURL || window).createObjectURL(new Blob([markdown])); // 建造本地临时url

                    var a = document.createElement("a"); // 建造链接元素
                    a.download = "下载.md"; // 设置文件名
                    a.href = objurl; // 设置链接

                    a.click(); // 模拟点击链接（下载文件）
                },
            },
            lang: {
                toolbar: { // 工具栏每个内容的工具提示
                    upload: "导入 .md / .txt 文件",
                    download: "导出为 .md 文件",
                }
            },
            onload() { // 加载完毕时
                clearInterval(loop);
                _this.resize();
                this.setToolbarAutoFixed(false); // 设置工具栏自动置顶为关
                this.config("pageBreak", true); // 允许分页
                this.setMarkdown(localStorage.getItem("ducksite_sendpost_markdown") || ""); // 设置内容为localStorage中的

                $('.app-post-input').prop("disabled", false);
                $('.app-post-release').prop("disabled", false);
            },
            onchange() { // 当内容变化时，将内容保存到localStorage
                window.onbeforeunload = () => true;
                _this.resize();
                const markdown = this.getMarkdown();
                localStorage.setItem("ducksite_sendpost_markdown", markdown);
            }
        });
    };

    release() {  // 发布
        if (!this.checkPost($('.app-post-input').val(), this.editor.getMarkdown())) {
            return dsnackbar('warning', "字数过多或填写不完整");
        }

        // 请求载荷
        const data = {
            title: $('.app-post-input').val(),
            markdown: btoa(
                encodeURIComponent(this.editor.getMarkdown()).replace(
                    /%([0-9A-F]{2})/g,
                    function (match, p1) {
                        return String.fromCharCode('0x' + p1);
                    }
                )
            ),
            partition_id: $(".app-post-pa input:checked").val(),
        };

        $('.app-post-input, .app-post-release').prop("disabled", true);
        $('#test-editor, .app-post-pa').css("pointerEvents", "none");

        // 发送POST请求
        fetch('/api/shequ/send_post/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        }).then(response => response.json())
            .then(result => {
                if (result.code == 200) { // 状态码为200（成功）
                    window.onbeforeunload = null;
                    localStorage.setItem("ducksite_sendpost_title", "");
                    localStorage.setItem("ducksite_sendpost_markdown", "");
                    swal.skip({
                        title: "发帖成功",
                        to: "帖子页面",
                        src: "/post/" + result.data
                    });
                } else {
                    $('.app-post-input, .app-post-release').prop("disabled", false);
                    $('#test-editor, .app-post-pa').css("pointerEvents", "");
                    dsnackbar('error', result.msg);
                }
            })
            .catch(() => {
                $('.app-post-input, .app-post-release').prop("disabled", false);
                $('#test-editor, .app-post-pa').css("pointerEvents", "");
                dsnackbar('error', "请稍后再试");
            })
    }

    renderPartition() { // 分区
        var loadingText = $("<p>加载中</p>");
        loadingText.appendTo(".app-post-pa");

        $.ajax('/api/shequ/get_post_partition/?t=' + Date.now(), {
            contentType: 'application/json',
        }).done(response => {
            loadingText.remove();

            if (response.code == 200) { // 如果状态码为200

                for (let va of response.data) { // 渲染
                    let el = $("<label>");

                    let el1 = $("<input>");
                    el1.attr("type", "radio");
                    el1.attr("name", "app-post-pa-radio");
                    el1.prop("value", String(va.id));

                    let el2 = $("<span>");
                    el2.text(va.name);

                    el.append(el1, el2);
                    $(".app-post-pa").append(el);
                }
                $(".app-post-pa input").first().prop("checked", true)
            } else {
                $(".app-post-pa").append(`<p>${response.msg}</p>`);
            }
        }).fail(() => {
            $(".app-post-pa").append("<p>加载出错</p>");
        });
    };

    initTitle() { // 初始化标题
        const input = $('.app-post-input');
        const release = $('.app-post-release');

        // 加载localStorage中的标题
        const title = localStorage.getItem("ducksite_sendpost_title");
        if (title) input.val(title);

        input.on('change', () => { // 标题变化时，将标题保存到localStorage
            localStorage.setItem("ducksite_sendpost_title", input.val());
        });

        release.on('click', () => { // 发布按钮点击事件
            this.release();
        });

        this.renderPartition();
    };
}])